package com.ssm.demo.util.aspect;

/**
 * @date 2023-11-19
 * @author Zhang Yu
 */

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import jakarta.servlet.http.HttpServletRequest;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * @description:打印请求和响应信息
 */
@Aspect
@Component
@Slf4j
public class WebLogAspect {


    @Pointcut("execution(public * com.ssm.demo.controller.*.*(..)))")
    public void webLog() {

    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        //分析并打印请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        log.info("request url:" + request.getRequestURL().toString());
        log.info("request method:" + request.getMethod());
        Object[] objects = joinPoint.getArgs();
        StringBuffer stringBuffer = new StringBuffer();
        for (Object object : objects) {
            if (object!=null && object.toString() != null) {
                stringBuffer.append(object.toString());
                stringBuffer.append("  |  ");
            }
        }
        log.info("args : " + stringBuffer);
    }

    @AfterReturning(returning = "res", pointcut = "webLog()")
    public void doAfterReturning(Object res) throws JsonProcessingException {
        log.info("return response : " + new ObjectMapper().writeValueAsString(res));
    }

}